from model.Teacher import Teacher
from controller.Base import BaseHandler
from tornado import gen


# m : method
class TeacherHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        try:
            method = self.get_argument("m")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)

        # 类型检查
        if not method.isdigit():
            return self.write(self.response_code.PARAM_TYPE_BIND_ERROR)

        method = int(method)
        t = self.response_code.SUCCESS.copy()
        if method == 1:
            # 按页获取所有教师
            try:
                page_num = self.get_argument("page")
            except Exception as e:
                return self.write(self.response_code.PARAM_NOT_COMPLETE)
            data = yield Teacher.get_all(page_num)
            count = yield Teacher.get_count()
        elif method == 0:
            # 通过职工号查找教师
            try:
                t_id = self.get_argument("tid")
            except Exception as e:
                return self.write(self.response_code.PARAM_NOT_COMPLETE)
            data = yield Teacher.get_by_id(t_id)
            data = (data,)
            count = 1
        else:
            return self.write(self.response_code.PARAM_IS_INVALID)
        t["data"] = data
        t["total"] = count
        return self.write(t)

    @gen.coroutine
    def post(self):
        try:
            t_id = self.get_argument("tid")
            t_name = self.get_argument("tname")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)

        result = yield Teacher.add(t_id, t_name)
        if result:
            self.write(self.response_code.SUCCESS)
        else:
            self.write(self.response_code.USER_HAS_EXISTED)

    @gen.coroutine
    def put(self):
        pass

    @gen.coroutine
    def delete(self):
        try:
            t_id = self.get_argument("id")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)
        result = Teacher.del_by_id(t_id)
        if result:
            self.write(self.response_code.SUCCESS)
        else:
            self.write(self.response_code.USER_NOT_EXIST)

